<?php
declare (strict_types=1);

namespace app\api\controller;

use app\api\business\Jwt;
use app\api\validate\User;
use app\BaseController;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;

class Login extends BaseController
{
//    验证码
    public function index()
    {
//        验证码标识
        $id = mt_rand(100000, 999999);
        $uniqid = uniqid("$id");
        //返回数据 验证码图片路径、验证码标识
        $data = [
            'src' => "http://www.pyg.com" . captcha_src($uniqid),
            'uniqid' => $uniqid
        ];
        return json($data);
    }

    public function login()
    {
        $data = \request()->all();
        try {
            validate(User::class)->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return fail($e->getError());
        }
//       验证账号密码
        $loginDate = Db::table('pyg_admin')->where('username', '=', $data['username'])->find();
        if (!$loginDate) {
            return fail("用户名不存在");
        }
        $password = pwd($data['password']);
        if ($loginDate['password'] != $password) {
            return fail("密码不正确");
        }
        $token = \app\api\business\Jwt::createjwt($loginDate['id']);
        $backDate = [
            'token' => $token,
            'user_id' => $loginDate['id'],
            'username' => $loginDate['username'],
            'nickname' => $loginDate['nickname'],
            'email' => $loginDate['email']
        ];
        return success($backDate, 200, 'success');
    }


    public function logout()
    {
        //取出token值
        $token = Jwt::getRequestToken();
        try {
            // 验证token值
            $res = Jwt::verifyjwt($token);
        } catch (\Exception $exception) {
            return fail($exception->getMessage());
        }
        //查看缓存中是否有存在delete_token这个键
        $delete_token = cache('delete_token') ?: [];
        //将token值放入delete_token数组中
        $delete_token[] = $token;
        // 将数组塞回缓存中
        cache('delete_t0ken', $delete_token);
        // 销毁成功
        return success(1);
    }
}
